<template>
  <div class="basic_info">
    <div class="info_operation_btn">
      <div class="btn_left">
        <el-button type="primary" @click="requestQuery">统计</el-button>
        <el-button @click="exportExcel">导出</el-button>
        <el-button @click="handleShortcutKeyPrint">打印(P)</el-button>
        <el-checkbox v-model="queryData.hideZero" @change="requestQuery">不显示本期未创利的往来单位</el-checkbox>
      </div>
      <div class="btn_right">
        <el-select @change="changeDate" v-model="monthValue">
          <el-option v-for="item in monthOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <el-date-picker v-model="nowDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" @change="onClickPicker" value-format="yyyy-MM-dd"></el-date-picker>
        <el-button type="primary" @click="requestQuery">查询</el-button>
        <i @click="onShowColumn()" class="set_up el-icon-s-tools"></i>
      </div>
    </div>
    <div class="info_content_div">
      <div class="div_tree">
        <div class="tree_div1">
          <p>往来单位类别</p>
        </div>
        <div class="tree_input">
          <p>
            <input type="text" placeholder="查找" v-model="lookupValue" />
            <span>
              <i class="el-icon-search"></i>
            </span>
          </p>
        </div>
        <div class="tree_structure">
          <el-tree ref="tree" :data="treeData" node-key="id" :props="{
            label: 'companyTypeName'
          }" highlight-current default-expand-all :expand-on-click-node="false" @node-click="handleNodeClick"
            :filter-node-method="filterNode"></el-tree>
        </div>
      </div>
      <div class="div_table">
        <div class="table_content">
          <el-table ref="tableList" show-summary :summary-method="getSummaries" highlight-current-row :header-cell-style="{
            background: '#E3F6FF',
            color: '#666666',
            textAlign: 'center',
            height: '30px',
            borderColor: '#dddddd',
          }" border :cell-style="{ textAlign: 'center' }" :data="tableData" height="100%" style="width: 100%">
            <template v-for="(item, index) in columnData">
              <el-table-column :show-overflow-tooltip="true" :key="index"
                :label="item.zidingyiName ? item.zidingyiName : item.morenName" v-if="item.zidingyiState"
                :prop="item.props" min-width="120px" :width="item.props == 'xh' ? '50px' : ''"
                :sortable="item.props != 'xh'">
                <template slot-scope="scope">
                  <span v-if="arr.includes(item.props)">{{ $formatMoney(scope.row[item.props]) }}</span>
                  <span v-else>{{ scope.row[item.props] }}</span>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>
        <div class="table_pagination">
          <div class="pagination_div">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="currentPage" :page-sizes="[20, 50, 100, 200]" :page-size="pagesize"
              layout="jumper, prev, pager,next, sizes" :total="total"></el-pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 列配置弹框 -->
    <!-- <CConfiguration ref="setColumnRef" :columnDataArr="columnData" orderType="客户创利统计" @onSaveColumn="onSaveColumn"> -->
      <CConfiguration
      ref="setColumnRef"
      :columnDataArr="columnData"
      :defaultColumnDataArr="defaultColumnData"
      orderType="客户创利统计"
      @onSaveColumn="onSaveColumn"
    ></CConfiguration>
    </CConfiguration>
    <!-- 打印 -->
    <dialog-print ref="print"></dialog-print>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import CConfiguration from '@/components/c_column/columnConfiguration1'
/**打印 */
import dialogPrint from '@/views/components/dialogPrintStatic'
import { getAction, postAction, downPostFile } from '@/api/manage'
import { dateStrFromDate } from '@/utils/DateFormatter'
import { getTreeDataByMap, getTreeAllSubId } from "@/utils";
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { handlePermissions, handleOtherPerms } from '@/utils/index'
import { delcommafy, formatMoney } from '../../../utils'
export default {
  name: 'customerProfitability',
  components: {
    CConfiguration,
    dialogPrint,
  },
  mixins: [JeecgListMixin],
  computed: {
    ...mapGetters(['name']),
    buttonsPermissions() {
      return handlePermissions('客户创利统计')
    },
    printPermissions() {
      return handleOtherPerms('单据可多次打印')
    },
  },
  created() {
    // 默认获取当月时间
    this.getTimeRange(this.$setTimeRange(5))
    this.getData()
  },
  data() {
    return {
      queryData: {
        startDate: '',
        endDate: '',
        hideZero: false,
        // companyIdList: [],
        companyTypeIds: []
      },
      // 时间区间选择
      monthValue: '本月',
      monthOptions: [
        {
          value: '今日',
          label: '今日',
        },
        {
          value: '本周',
          label: '本周',
        },
        {
          value: '本月',
          label: '本月',
        },
        {
          value: '本年',
          label: '本年',
        },
      ],
      nowDate: [],
      // 类别数据
      lookupValue: '', //类别查找值
      treeData: [],
      // 表格数据
      tableData: [],
      // 列配置数据
      defaultColumnData: [],
      columnData: [
        {
          morenName: '序号',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: true,
          props: 'xh',
        },
        {
          morenName: '往来单位编号',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'companyNumber',
        },
        {
          morenName: '往来单位名称',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'companyId_dictText',
        },
        {
          morenName: '销售金额',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'salePrice',
        },
        {
          morenName: '整单优惠',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'saleDiscountPrice',
        },
        {
          morenName: '销售成本',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'saleCostPrice',
        },
        {
          morenName: '销售毛利',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'saleGrossProfit',
        },
        {
          morenName: '毛利率',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'saleGrossProfitRate',
        },
        {
          morenName: '其他收入',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'otherIncome',
        },
        {
          morenName: '费用支出',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'expense',
        },
        {
          morenName: '本期利润',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'profit',
        },
        {
          morenName: '本期回款',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'settlementPrice',
        },
      ],
      total: 0,
      pagesize: 20, //每页的数据条数
      currentPage: 1, //默认开始页面
      updateId: '', // 修改列配置时返回的id
      url: {
        listUrl: '/financialstatements/customercreationstatistics/count',
        api: '客户创利统计',
        companyList: '/xghCompanyType/xghCompanyType/childList',
        exportXlsUrl: '/financialstatements/customercreationstatistics/exportXls'
      },
      arr: ['salePrice', 'saleDiscountPrice', 'saleCostPrice', 'saleGrossProfit', 'profit', 'settlementPrice', 'otherIncome', 'expense'],
      pageName: '客户创利统计',
    }
  },
  mounted() {
  },
  watch: {
    lookupValue(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    // 打印
    async handleShortcutKeyPrint() {
      // 查询
      let parmas = {
        ...this.queryData,
        pageNo: 1,
        pageSize: 1000000,
      }
      let printExclusive = []
      const res = await postAction(this.url.listUrl, parmas)
      if (res.success) {
        let list = res.result.records || []
        printExclusive = list.map((item, index) => {
          item.xh = index + 1
          item.saleGrossProfitRate = item.saleGrossProfitRate + '%'
          item.salePrice = formatMoney(item.salePrice)
          item.saleDiscountPrice = formatMoney(item.saleDiscountPrice)
          item.saleCostPrice = formatMoney(item.saleCostPrice)
          item.saleGrossProfit = formatMoney(item.saleGrossProfit)
          item.profit = formatMoney(item.profit)
          item.settlementPrice = formatMoney(item.settlementPrice)
          item.otherIncome = formatMoney(item.otherIncome)
          item.expense = formatMoney(item.expense)
          return item
        })
      }
      this.requestQuery()
      // 打印
      if (!this.buttonsPermissions.DaYin) {
        this.$elMessage.warning('未拥有打印权限！')
      } else if (!printExclusive || printExclusive.length <= 0) {
        this.$elMessage.warning('没有要打印的记录！')
      } else {
        let printData = {
          riqi: this.queryData.startDate + '~' + this.queryData.endDate,
          printExclusive,
        }
        // 可以多次打印设置
        if (this.printPermissions) {
          this.$refs.print.show(printData, this.columnData, this.pageName)
        } else {
          if (this.$lcStorage.get('printLimitValue')) {
            // 获取打印次数
            this.getPrintNum(this.pageName, (() => {
              this.$refs.print.show(printData, this.columnData, this.pageName)
            }))
          } else {
            this.$refs.print.show(printData, this.columnData, this.pageName)
          }
        }
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.companyTypeName.indexOf(value) !== -1;
    },
    // 触发树形当前节点
    handleNodeClick(data) {
      console.log('往来单位类别选择', data)
      if (data.id != '0') {
        let result = []
        getTreeAllSubId(data, result, true)
        console.log(result);
        this.queryData.companyTypeIds = result //.join(',')
      } else {
        this.queryData.companyTypeIds = undefined
      }
      this.currentPage = 1
      this.requestQuery()
    },
    // 初始化查询列配置值
    async selectTitle() {
      let obj = await this.$setColumn.selectColumn(this.url.api)
      if (obj.code === 200) {
        this.updateId = obj.updateId
        this.columnData = obj.columnData
      } else if (obj.code === 500) {
        let id = await this.$setColumn.addColumn(this.url.api, this.columnData)
        this.updateId = id
      }
    },
    // 修改列配置后保存修改后的值
    async onSaveColumn(value) {
      this.columnData = value
      let res = await this.$setColumn.editColumn(this.url.api, this.columnData, this.updateId)
      if (res.code == 200) {
        this.$elMessage.success(res.message)
      } else {
        this.$elMessage.error(res.message)
      }
    },
    // 导出
    exportExcel() {
      let queryParam = {
        ...this.queryData,
        fileName: '客户创利统计',
      }
      this.handleExportXlsByStaff('客户创利统计', queryParam)
    },
    // 获取数据
    getData() {
      this.getTreeData()
      this.selectTitle()
      this.requestQuery()
    },
    getTreeData() {
      getAction(this.url.companyList, {}).then((res) => {
        if (res.code === 200) {
          let list = res.result || []
          let result = getTreeDataByMap(list)
          this.treeData = [{
            id: '0',
            companyTypeName: '全部',
            children: result
          }]
          console.log(this.treeData);
        }
      })
    },
    // 请求筛选条件数据
    requestQuery(obj) {
      let parmas = {
        ...this.queryData,
        pageNo: this.currentPage,
        pageSize: this.pagesize
      }
      postAction(this.url.listUrl, parmas).then(res => {
        console.log(res);
        if (res.success) {
          let list = res.result.records
          this.total = res.result.total
          this.tableData = list.map((item, index) => {
            item.xh = index + 1
            item.saleGrossProfitRate = (item.saleGrossProfitRate || '0') + '%'
            return item
          })
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    // 判断当前选择时间段
    changeDate(val) {
      switch (val) {
        case '全部':
          this.getTimeRange({
            now: '',
            end: ''
          })
          break
        case '今日':
          this.getTimeRange(this.$setTimeRange(1))
          break
        case '昨天':
          this.getTimeRange(this.$setTimeRange(2))
          break
        case '本周':
          this.getTimeRange(this.$setTimeRange(3))
          break
        case '上周':
          this.getTimeRange(this.$setTimeRange(4))
          break
        case '本月':
          this.getTimeRange(this.$setTimeRange(5))
          break
        case '上月':
          this.getTimeRange(this.$setTimeRange(6))
          break
        case '本年':
          this.getTimeRange(this.$setTimeRange(7))
          break
        case '去年':
          this.getTimeRange(this.$setTimeRange(8))
          break
        default:
          break
      }
    },
    // 获取时间范围并设置
    getTimeRange(data) {
      this.nowDate = [data.now, data.end]
      this.queryData.startDate = data.now
      this.queryData.endDate = data.end
    },
    // 获取当前选中时间
    onClickPicker(val) {
      this.queryData.startDate = val[0]
      this.queryData.endDate = val[1]
    },
    // 触发列配置弹框
    onShowColumn() {
      this.defaultColumnData = this.$options.data().columnData
      this.$refs.setColumnRef.dialogVisible = true
    },
    // 合计列计算
    getSummaries(param) {
      this.$nextTick(() => {
        this.$refs.tableList.doLayout();
      })
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 1) {
          sums[index] = '共' + this.total + '条明细'
        } else if (this.arr.includes(column.property)) {
          const values = data.map((item) => delcommafy(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = delcommafy(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = this.$formatMoney(sums[index])
          } else {
            sums[index] = ''
          }
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 获取每页几条数据
    handleSizeChange(val) {
      this.pagesize = val
      this.requestQuery()
    },
    // 获取当前第几页
    handleCurrentChange(val) {
      this.currentPage = val
      this.requestQuery()
    },
  },
}
</script>

<style lang="scss" scoped>
.basic_info {
  width: 100%;
  height: 100%;
  background: #f0f2f5;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.info_operation_btn {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  ::v-deep .el-button {
    width: 70px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    margin-right: 10px;
    margin-left: 0;
  }

  .el-button--default {
    color: #666;
    border: none;
  }

  .el-button--default:hover {
    background-color: #ffffff;
  }

  ::v-deep .el-checkbox {
    display: flex;
    align-items: center;
    margin-right: 0.25rem;

    .el-checkbox__input {
      height: 14px;
    }

    .el-checkbox__label {
      font-size: 12px;
      padding-left: 0.1rem;
      color: #666;
    }

    .is-checked {
      .el-checkbox__inner {
        background: #1a93fa;
        border-color: #1a93fa;
      }
    }
  }

  ::v-deep .el-select {
    width: 80px;
    height: 30px;
    box-sizing: border-box;
    margin-right: 0.112507rem;

    .el-input {
      .el-input__inner {
        height: 30px;
        border: none;
        font-size: 12px;
      }

      .el-input__suffix {
        height: 30px;
        display: flex;
        align-items: center;
      }
    }
  }

  ::v-deep .el-date-editor {
    width: 220px;
    height: 30px;
    background: #ffffff;
    border: 1px solid #d9d9d9;
    margin-right: 0.112507rem;
    padding: 3px 6px;

    .el-range__icon {
      position: absolute;
      right: 0;
      line-height: 30px;
    }

    .el-range-separator {
      line-height: 24px;
    }

    .el-range-input {
      font-size: 12px;
    }

    .el-range__close-icon {
      display: none;
    }
  }

  .btn_left {
    width: 60%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .btn_right {
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .set_up {
      font-size: 20px;
      color: rgb(153, 153, 153);
    }
  }
}

.info_content_div {
  width: 100%;
  height: calc(100% - 60px);
  margin-top: 10px;
  background-color: #ffffff;
  padding: 10px;
  display: flex;

  .div_tree {
    width: 2.8rem;
    height: calc(100% - 50px);
    box-sizing: border-box;
    // padding: 10px 0;
    border: 0.018751rem solid #e3e3e3;
    transition: all 0.3s;
    margin-right: 10px;

    .tree_div1 {
      width: 100%;
      height: 34px;
      box-sizing: border-box;
      padding: 0 0.168761rem;
      display: flex;
      align-items: center;
      justify-content: space-between;

      p {
        color: #666666;
        font-size: 12px;
        margin: 0;
      }
    }

    .tree_input {
      width: 100%;
      height: 30px;
      box-sizing: border-box;
      padding: 0 0.168761rem;

      p {
        width: 100%;
        height: 30px;
        margin: 0;
        box-sizing: border-box;
        border: 1px solid #dddddd;
        display: flex;
        align-items: center;
        position: relative;

        input {
          width: 100%;
          box-sizing: border-box;
          padding: 0 0.6rem 0 0.1rem;
          height: 28px;
          border: none;
          font-size: 12px;

          &:focus {
            outline: none;
          }
        }

        span {
          position: absolute;
          right: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 0.55rem;
          height: 28px;
          background: #fff;

          .el-icon-search {
            font-size: 20px;
            color: rgb(211, 211, 211);
          }
        }
      }
    }

    .tree_structure {
      width: 100%;
      height: calc(100% - 84px);
      box-sizing: border-box;
      padding: 0 0.168761rem;
      margin-top: 10px;
      overflow: auto;

      ::v-deep .el-tree {
        width: 100%;

        .el-tree-node__children {
          .el-tree-node__label {
            color: #666;
            font-weight: normal;
          }
        }

        .el-tree-node__label {
          font-size: 12px;
          font-weight: 600;
        }

        .el-tree-node__content>.el-tree-node__expand-icon {
          padding-left: 0;
        }
      }
    }
  }

  .div_table {
    width: calc(100% - 3rem);
    height: 100%;

    .table_content {
      height: calc(100% - 50px);

      ::v-deep .el-table {
        border-color: #ddd;
        box-sizing: border-box;

        th,
        td {
          padding: 0;
          color: #666;
        }

        .el-table__header {
          tr {
            &:last-child {
              th {
                background: rgb(237, 237, 237) !important;
              }
            }
          }
        }

        .cell {
          line-height: 30px;
          font-size: 12px;
        }

        .el-table__body tr:hover>td {
          background: #e3f6ff;
        }

        .el-table__footer-wrapper {
          td {
            background: #f4f4f4;
            border: none;
          }
        }

        //滚动条的宽度
        ::-webkit-scrollbar {
          width: 8px;
          height: 10px;
          background-color: #e5e5e5;
        }

        //滚动条的滑块
        ::-webkit-scrollbar-thumb {
          background-color: #c9c9c9;
        }
      }
    }

    .table_pagination {
      width: 100%;
      height: 50px;
      box-sizing: border-box;
      padding: 10px 0;
      display: flex;

      .pagination_div {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        ::v-deep .el-pagination {
          padding: 0;
          height: 30px;

          .el-pagination__sizes {
            margin: 0;

            .el-input {
              margin-right: 0;
            }
          }
        }
      }
    }
  }
}
</style>